﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using OnlineManagement.Web.WebBLL;
using OnlineManagement.Model;

namespace OnlineManagement.Web.Account
{
    public partial class Register : System.Web.UI.Page
    {

        protected void Page_Load(object sender, EventArgs e)
        {
            //RegisterUser.ContinueDestinationPageUrl = Request.QueryString["ReturnUrl"];
            btnRegister.Click += new EventHandler(btnRegister_Click);
            if (!Page.IsPostBack)
            {
                if (Request.UrlReferrer != null) hidden.Value = Request.UrlReferrer.ToString();
                string requestUrl = Request.Url.ToString();
                int count = requestUrl.LastIndexOf('/');
                string postUrl = requestUrl.Substring(0, count);
                postUrl = postUrl.Substring(0, postUrl.LastIndexOf('/'));
                authcode_img.ImageUrl = string.Format("{0}/Account/Auth.aspx", postUrl);
            }
        }

        void btnRegister_Click(object sender, EventArgs e)
        {
            string name = userName.Value;
            if(string.IsNullOrEmpty(name)){
                tips_userName.InnerHtml = "<div class=\"wt01\" id=\"tips_userName\"><span>用户名不能为空</span></div>";
                CleanControls();
                return;
            }
            string passwordStr = password1.Value;
            string password2Str = password2.Value;
            if(string.IsNullOrEmpty(passwordStr)||
                string.IsNullOrEmpty(password2Str)||
                passwordStr!=password2Str){
                    tips_password1.InnerHtml = "<div id=\"tips_password1\" class=\"wt01\"><span>密码设置错误，请检测密码是否为空或两次输入的密码是否一致</span></div>";
                    CleanControls();
                    return;
            }
            string code = identity.Value;
            if(string.IsNullOrEmpty(code)){
                tips_authcode.InnerHtml = " <div id=\"tips_authcode\" runat=\"server\" class=\"wt01\"><span>验证码不能为空</span></div>";
                CleanControls();
                return;
            }
            if (Session["code"] != null && code == Session["code"].ToString())
            {
                SubmitRegister();
            }
            else {
                tips_authcode.InnerHtml = " <div id=\"tips_authcode\" runat=\"server\" class=\"wt01\"><span>验证码错误，请重新输入</span></div>";
                CleanControls();
                return;
            }

        }

        private void SubmitRegister() {
            int hoggeryId = 0;
            try
            {
                UserManagement userManagement = new UserManagement();
                TempRegistUsers user = new TempRegistUsers()
                {
                    LoginName = userName.Value,
                    Password = password1.Value,
                    HoggeryManager = txtHoggeryManager.Value,
                    HoggeryName = txtHoggeryName.Value
                };
                
                RegisterMsg msg = userManagement.TempRegestUser(user,out hoggeryId);
                if (msg != null && msg.Flag && hoggeryId > 0)
                {
                    FormsAuthentication.Initialize();
                    Membership.ValidateUser(userName.Value, password1.Value);
                    FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,
                                          userName.Value,
                                          DateTime.Now,
                                          DateTime.Now.AddMinutes(30),
                                          true,
                                          hoggeryId.ToString(),//用户所属的角色字符串 
                                          FormsAuthentication.FormsCookiePath);
                    string hash = FormsAuthentication.Encrypt(ticket);
                    HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hash);
                    if (ticket.IsPersistent)
                    {
                        cookie.Expires = ticket.Expiration;
                    }
                    //把准备好的cookie加入到响应流中 
                    Response.Cookies.Add(cookie);

                    ////转发到请求的页面 
                    Response.Redirect(FormsAuthentication.GetRedirectUrl(userName.Value, false));
                }
                else {
                    regstat.InnerText = msg.Message;
                }

            }catch(Exception ex){
                Common.MessageBox.Show(this, Common.PubMsg.ServerError);
                CleanControls();
            }
        }

        private void CleanControls() {
            userName.Value = string.Empty;
            password1.Value = string.Empty;
            password2.Value = string.Empty;
            identity.Value = string.Empty;
        }
       

    }
}
